import axios from 'axios'
import {Message, MessageBox, Notification} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import merge from 'lodash/merge'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
var dateMap = new Map();
dateMap.set('zh','zh-CN,zh;q=0.9')
dateMap.set('en','en-US,en;q=0.9')
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
   baseURL: process.env.VUE_APP_BASE_API,
  //baseURL: 'https://mojin.51wangshi.com/api-admin',
  // 超时
  timeout: 10000000
})
// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  config.headers['Accept-Language'] =dateMap.get(store.getters.language)
  //store.getters.language
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const message = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 401) {
      console.log(res.config.url)
      if( res.config.url.indexOf('baseinfoset')!=-1){

      }else{
        MessageBox.confirm(
          '登录状态已过期，您可以继续留在该页面，或者重新登录',
          '系统提示',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      }

    } else if (code === 500) {
      Message({
        message: message,
        type: 'error'
      })
      return Promise.reject(new Error(message))
    } else if (code !== 200) {
      Notification.error({
        title: message
      })
      return Promise.reject('error')
    } else {
    console.log(res)
    if(res.config.url.indexOf("/wx") != -1){
      return res
    }
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
service.adornUrl = (actionName) => {
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!
  return  actionName
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
service.adornParams = (params = {}, openDefultParams = true) => {
  var defaults = {
    't': new Date().getTime()
  }
  return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
service.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
  var defaults = {
    't': new Date().getTime()
  }
  data = openDefultdata ? merge(defaults, data) : data
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}
export default service
/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
 export function post(url, data = {}) {
   return new Promise((resolve, reject) => {
     service.post(url, data)
       .then(response => {
         resolve(response)
       }, err => {
         reject(err)
       })
   })
 }

export function get(url, data = {}) {
  return new Promise((resolve, reject) => {
    service.get(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}
export function del(url, data = {}) {
  return new Promise((resolve, reject) => {
    service.delete(url, data)
      .then(response => {
        resolve(response)
      }, err => {
        reject(err)
      })
  })
}
